<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\libs\PaypalSDK\action\PurchasePaypal;
use app\libs\PaypalSDK\builder\QuickPayBuilder;
use app\model\IpLogs;
use app\model\Notify;
use app\model\ShopsPayment;
use app\service\payment\gateway\PaypalService;
use app\service\shopify\action\admin\ShopifyPay;
use app\service\shopify\action\graph\CartGraph;
use app\service\shopify\action\store\CartStore;
use app\service\shopify\action\store\Payment;
use app\service\shopify\ShopifyApiService;
use app\trait\OrderTrait;
use app\trait\ShopifyTrait;
use think\exception\ValidateException;
use think\helper\Arr;
use think\Request;

class CheckoutController extends BaseController
{
    use OrderTrait, ShopifyTrait;
    //创建结账ID
    public function createCheckout(Request $request)
    {
        IpLogs::saveIpLogs($request,IpLogs::LP_TYPE_BUY_NOW);//保存点击按钮信息
        $x_shop_id = $request->x_shop_id;
        $paypal = ShopsPayment::query()->where('shop_id',$x_shop_id)->where('pay_method',ShopsPayment::PAY_METHOD_PAYPAL)->findOrEmpty();
        //预支付
        if(!$paypal->isExists()){
            $paypal = [
                'payment_id'=>0,
                'paypal_client_id'=>'',
                'mode'=>CommonConstant::MODE_SANDBOX_WORD
            ];
        }else{
            $config = $paypal->config;
            $paypal = [
                'payment_id'=>$paypal->id,
                'paypal_client_id'=>Arr::get($config,'app_key',''),
                'mode'=>Arr::get($config,'env',''),
            ];
        }

        $checkout = $request->post('checkout',[]);
        $btn_uid = Arr::get($checkout,"btn_uid",'prod_page_checkout');
        $defaultResponse = [
            'checkout'=>[
                'action'=>'live',
                'id'=>'',
                'funnel_type'=>'opc',
                'btn_uid'=>$btn_uid,
                'approval_url'=>'',
                'paypal'=>$paypal,
                'pay_step'=>$request->x_pay_step
            ]
        ];
        if(empty($checkout)) return json($defaultResponse);
        $checkoutId = $this->createCheckoutId($request);
        if($btn_uid == 'prod_page_paypal'){
            $order = $this->saveOrder($request);
            $order->pay_id = Arr::get($paypal,'payment_id');
            $order->pay_method = ShopsPayment::PAY_METHOD_PAYPAL;
            $order->is_paypal_kj = ModelConstant::STATUS_ON;
            $order->paypal_method = $request->param('paypal_method', 0);
            $order->checkout_id = $checkoutId;
            $order->save();
            $service = new PaypalService();
            $quickRes = $service->quickPay($request,$order);
            $defaultResponse['checkout']['approval_url'] = Arr::get($quickRes,'approval_url','');
        }
        $defaultResponse['checkout']['id'] = $checkoutId;
        return json($defaultResponse);

    }





}
